package utils;

import cn.hutool.core.collection.CollectionUtil;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfArray;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfNumber;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.canvas.draw.DottedLine;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Tab;
import com.itextpdf.layout.element.TabStop;
import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.property.Property;
import com.itextpdf.layout.property.TabAlignment;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.*;
import org.apache.pdfbox.rendering.ImageType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class PdfUtils {
    private static final Logger log = LoggerFactory.getLogger(PdfUtils.class);

    public static void main(String[] args){
        // 压缩文件

        List<String> pdfurl = Arrays.asList(
                "D:/upFiles/03f9ae4b-1be4-4dff-b0f5-ffefc4045715.pdf",
                "D:/upFiles/519a667d-e7de-423c-95ea-4007482fb9f2.pdf",
                "D:/upFiles/2aac27da-f0ce-49ef-a424-ea02fcdc41d2.pdf");
//        String outurl = "D:/upFiles/mergePdf_test.pdf";
//        PdfUtils.mergePdf(pdfurl,outurl);  // 合并pdf文件

        /** pdf转图片 ,图片转pdf */
        List<String> pdfurl2 = new ArrayList<>();
        for (String outurl : pdfurl) {
            List<String> imgUrlList = PdfUtils.pdf2Image(outurl, 200);
            int i = 1;
            if (CollectionUtil.isNotEmpty(imgUrlList)) {
                for (String imgUrl : imgUrlList) {
                    String outurl2 = "D:/upFiles/"+i+"-tpimg_" + UUID.randomUUID() + ".pdf";
                    pdfurl2.add(PdfUtils.img2Pdf(imgUrl, outurl2));
                    i++;
                    PdfUtils.deleteByCompleteUrl(imgUrl);
                }
            }
        }

        String outurl3 = "D:/upFiles/mergePdf_test3.pdf";
        PdfUtils.mergePdf(pdfurl2,outurl3); // 合并pdf文件
        if (CollectionUtil.isNotEmpty(pdfurl2)) {
            for (String delUrl : pdfurl2) {
                PdfUtils.deleteByCompleteUrl(delUrl);
            }
        }

        List<String> fileNames = Arrays.asList("目录1","目录2","目录3");
        Map<String, Object> catalogs = PdfUtils.getPdfMl(pdfurl,fileNames); // 获取目录

       int catalogPdfPageSize = 2;
        String outwjPdf = "D:/upFiles/mergePdf_test_ml.pdf";
        try {
//            PdfUtils.createPdfWithCatalog(outurl, outwjPdf, "合并PDF文件", catalogs, catalogPdfPageSize);
            PdfUtils.createPdfWithCatalog(outurl3, outwjPdf, "合并PDF文件", catalogs, catalogPdfPageSize);
//            deleteByCompleteUrl(outurl3);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 将多个pdf合并成一个pdf文件
     *
     * @auther: YSL
     * @date: 2022/8/2 16:46
     * @param sourceFilePaths  全路径
     * @param destFilePath  全路径
     */
    public static void mergePdf(List<String> sourceFilePaths, String destFilePath){
        if (sourceFilePaths == null || sourceFilePaths.isEmpty() || destFilePath == null) {
            return;
        }

        com.itextpdf.text.Document document = null;
        PdfCopy copy = null;
        OutputStream os = null;
        try {
            // 创建合并后的新文件的目录
//            Path dirPath = Paths.get(destFilePath.substring(0, destFilePath.lastIndexOf(File.separator)));
//            Files.createDirectories(dirPath);

            os = new BufferedOutputStream(new FileOutputStream(new File(destFilePath)));
            document = new com.itextpdf.text.Document(new PdfReader(sourceFilePaths.get(0)).getPageSize(1));
            copy = new PdfCopy(document, os);
            document.open();

//            int pagesSize = 0; //总页码
            int pageNo = 0; //当前页码

            for (String sourceFilePath : sourceFilePaths) {
                // 如果PDF文件不存在，则跳过
                if (!new File(sourceFilePath).exists()) {
                    continue;
                }

                PdfCopy.PageStamp stamp; // 插入页码

                // 读取需要合并的PDF文件
                PdfReader reader = new PdfReader(sourceFilePath);
                // 获取PDF文件总页数
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    pageNo++; // 当前页码

                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);

                    // 插入页码
                    stamp = copy.createPageStamp(page);
                    ColumnText.showTextAligned(
                            stamp.getUnderContent(),
                            Element.ALIGN_CENTER,
                            new com.itextpdf.text.Phrase(addFont(String.format("%d", pageNo))),
                            300f,16f,0f);//插入页码所需  不要页码可删除
                    stamp.alterContents();

                    copy.addPage(page);
                }
                reader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (copy != null) {
                try {
                    copy.close();
                } catch (Exception ex) {
                    /* ignore */
                }
            }
            if (document != null) {
                try {
                    document.close();
                } catch (Exception ex) {
                    /* ignore */
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (Exception ex) {
                    /* ignore */
                }
            }
        }
    }

    /**
     * 获取文件的页码
     * @param sourceFile
     * @return
     */
    public static Integer getPageNumber(String sourceFile){
        PdfDocument firstSourcePdf = null;
        try {
            firstSourcePdf = new PdfDocument(new com.itextpdf.kernel.pdf.PdfReader(sourceFile));
        } catch (IOException e) {
            e.printStackTrace();
        }
        int numberOfPages = firstSourcePdf.getNumberOfPages();
//        System.out.println("页码："+numberOfPages);
        firstSourcePdf.close();
        return numberOfPages;
    }

    /**
     * 获取页码目录
     * @param sourceFilePaths
     * @return
     */
    public static Map<String,Object> getPdfMl(List<String> sourceFilePaths,List<String> fileNames){
        Map<String,Object> mlMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(sourceFilePaths) && CollectionUtil.isNotEmpty(fileNames)){
                for (int i = 0; i<sourceFilePaths.size(); i++) {
                    if (!new File(sourceFilePaths.get(i).toString()).exists()){
                        continue;
                    }
                    // 获取pdf文件里面页码数
                    Integer pageNumber = PdfUtils.getPageNumber(sourceFilePaths.get(i).toString());
//                    System.out.println(fileNames.get(i).toString());

                    if (i != 0) {
                        Integer prePageNumber = 0;
                        if (i == 1){
                            // 获取第一个pdf文件的页码数
                            prePageNumber = PdfUtils.getPageNumber(sourceFilePaths.get(i-1).toString());
                        }else {
                            // 获取上一个文件的页码数
                            prePageNumber = (Integer) mlMap.get(fileNames.get(i - 1).toString());
                        }
//                        System.out.println("上一个: " + prePageNumber);
                        mlMap.put(fileNames.get(i).toString(), pageNumber+prePageNumber);
                    }else {
                        mlMap.put(fileNames.get(i).toString(), 1);
                    }

                }
        }
        return mlMap;
    }

    protected static com.itextpdf.text.Paragraph addFont(String content) {
        BaseFont baseFont = null;
        try {
            try {
//                baseFont=BaseFont.createFont("D:/z/simsun.ttc,0",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//D:/z/simsun.ttc,0是所下字体的路径
                baseFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
        Font font=null;
        font=new Font(baseFont,16f,Font.NORMAL);//设置字体
        return addText(content, font);
    }

    private static com.itextpdf.text.Paragraph addText(String content, Font font) {
        com.itextpdf.text.Paragraph paragraph = new com.itextpdf.text.Paragraph(content, font);
        paragraph.setAlignment(Element.ALIGN_LEFT);
        return paragraph;
    }

    /**
     * 生成一个带有目录(可跳转)的pdf文件(支持中文).
     * 如果目录两页,请为pdf多留出一页空白内容.
     * 此方法不能生成书签.
     *
     * @param sourceFile 源pdf文件
     * @param targetFile 带有目录(可跳转)的pdf文件
     * @param catalogs 目录数据map
     * @param catalogTitle 目录上方第一行文字
     * @param catalogPageSize 目录占页大小(为锚点偏移做参数)
     * @return targetFile
     * @throws IOException
     */

    public static String createPdfWithCatalog(String sourceFile,
                                              String targetFile,
                                              String catalogTitle,
                                              Map<String,Object> catalogs,
                                              int catalogPageSize) throws IOException {
        if (!new File(sourceFile).exists()){
            return targetFile;
        }
        Map<String,Object> catalogsTemp = new TreeMap<>();
        catalogsTemp.putAll(catalogs);
        //实际页码索引偏移量为 目录占页数-1
        int offset = catalogPageSize - 1;
        /*for (Map.Entry entry : catalogsTemp.entrySet()) {
            entry.setValue((Integer)entry.getValue() + offset);
        }*/

//        File file = new File(targetFile);
//        os = new BufferedOutputStream(new FileOutputStream(new File(targetFile)));
//        file.getParentFile().mkdirs();

        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(targetFile));
        Document document = new Document(pdfDoc);
        PdfFont font0 = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
//        PdfFont font0 = PdfFontFactory.createFont("C:/windows/Fonts//simsun.ttc");
        if (catalogTitle == null) {
            catalogTitle = " ";
        }

        document.add(new Paragraph(new Text(catalogTitle))
                .setTextAlignment(TextAlignment.CENTER).setFont(font0));
        PdfDocument firstSourcePdf = new PdfDocument(new com.itextpdf.kernel.pdf.PdfReader(sourceFile));
        int numberOfPages = firstSourcePdf.getNumberOfPages();
//        System.out.println("页码："+numberOfPages);
        for (int i = 1; i <= numberOfPages; i++) {
            PdfPage page = firstSourcePdf.getPage(i).copyTo(pdfDoc);
            pdfDoc.addPage(page);
            for (Map.Entry entry : catalogsTemp.entrySet()) {
                if (i == (int)entry.getValue()) {
                    String destinationKey = "p" + (pdfDoc.getNumberOfPages() - 1);
                    PdfArray destinationArray = new PdfArray();
                    destinationArray.add(page.getPdfObject());
                    destinationArray.add(PdfName.XYZ);
                    destinationArray.add(new PdfNumber(0));
                    destinationArray.add(new PdfNumber(page.getMediaBox().getHeight()));
                    destinationArray.add(new PdfNumber(1));
                    try {
                        pdfDoc.addNamedDestination(destinationKey, destinationArray);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    Paragraph p = new Paragraph();
                    PdfFont font = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
                    p.setFont(font);
                    p.addTabStops(new TabStop(540, TabAlignment.RIGHT, new DottedLine()));
                    p.add(entry.getKey().toString());
                    p.add(new Tab());
                    p.add(String.valueOf(pdfDoc.getNumberOfPages() - 1));
                    p.setProperty(Property.ACTION, PdfAction.createGoTo(destinationKey));
                    document.add(p);
                }

            }
        }

        firstSourcePdf.close();
        document.close();
        pdfDoc.close();

        return targetFile;

    }

    public static String createPdfWithCatalog2(String sourceFile,
                                              String targetFile,
                                              String catalogTitle,
                                              Map<String,Object> catalogs,
                                              int catalogPageSize) throws IOException {

        Map<String,Object> catalogsTemp = new TreeMap<>();
        catalogsTemp.putAll(catalogs);
        //实际页码索引偏移量为 目录占页数-1
//        int offset = catalogPageSize - 1;
        /*for (Map.Entry entry : catalogsTemp.entrySet()) {
            entry.setValue((Integer)entry.getValue() + offset);
        }*/

        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(targetFile));
        Document document = new Document(pdfDoc);
        PdfFont font0 = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
        if (catalogTitle == null) {
            catalogTitle = " ";
        }

//        document.add(new Paragraph(new Text(catalogTitle))
//                .setTextAlignment(TextAlignment.CENTER).setFont(font0));
        PdfDocument firstSourcePdf = new PdfDocument(new com.itextpdf.kernel.pdf.PdfReader(sourceFile).setUnethicalReading(true));
        int numberOfPages = firstSourcePdf.getNumberOfPages();
        for (int i = 1; i <= numberOfPages; i++) {
//            PdfPage page = firstSourcePdf.getPage(i);
            PdfPage page = firstSourcePdf.getPage(i).copyTo(pdfDoc);
            pdfDoc.addPage(page);

            // new
            /*PdfStream xmpMetadata = null;
            try {
                xmpMetadata = page.getXmpMetadata().copyTo(pdfDoc);
            } catch (XMPException e) {
                e.printStackTrace();
            }*/


            /** new */
           /* Rectangle orig = page.getPageSizeWithRotation();
            PdfPage pdfPage = pdfDoc.addNewPage(PageSize.A4.rotate());
            PdfCanvas canvas = new PdfCanvas(pdfPage);
            AffineTransform transformationMatrix = AffineTransform.getScaleInstance(
                    pdfPage.getPageSize().getWidth() / orig.getWidth(),
                    pdfPage.getPageSize().getHeight() / orig.getHeight());
            canvas.concatMatrix(transformationMatrix);
            PdfFormXObject pageCopy  = page.copyAsFormXObject(pdfDoc);
            canvas.addXObject(pageCopy,0,0);
            pdfDoc.addPage(page.copyTo(pdfDoc));*/


//            for (Map.Entry entry : catalogsTemp.entrySet()) {
//                if (i == (int)entry.getValue()) {
//                    String destinationKey = "p" + (pdfDoc.getNumberOfPages() - 1);
//                    PdfArray destinationArray = new PdfArray();
//                    destinationArray.add(page.getPdfObject());
//                    System.out.println(page.getPdfObject());
//                    destinationArray.add(PdfName.XYZ);
//                    destinationArray.add(new PdfNumber(0));
//                    destinationArray.add(new PdfNumber(page.getMediaBox().getHeight()));
//                    destinationArray.add(new PdfNumber(1));
//                    try {
//                        pdfDoc.addNamedDestination(destinationKey, destinationArray);
//                    } catch (Exception e) {
//                        System.out.println(e.getMessage());
//                    }
//                    Paragraph p = new Paragraph();
//                    PdfFont font = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
//                    p.setFont(font);
//                    p.addTabStops(new TabStop(540, TabAlignment.RIGHT, new DottedLine()));
//                    p.add(entry.getKey().toString());
//                    p.add(new Tab());
//                    p.add(String.valueOf(pdfDoc.getNumberOfPages() - 1));
//                    p.setProperty(Property.ACTION, PdfAction.createGoTo(destinationKey));
//                    document.add(p);
//                }
//            }
        }

        document.close();
        firstSourcePdf.close();
        pdfDoc.close();

        /**********/


        /**********/

        return targetFile;

    }

    /**
     * 新改的方法 ,生成目录pdf ,只是为了方便计算页数.
     * 基于createPdfWithCatalog()代码改编,该方法进保留生成目录功能.
     *
     * @param sourceFile sourceFile
     * @param targetFile targetFile
     * @param catalogs catalogs
     * @return 目录页数 page size
     * @throws IOException IOException
     */

    public static int createCatalogPdfOnly(String sourceFile, String targetFile, Map<String,Object> catalogs) throws IOException {

        File file = new File(targetFile);

        file.getParentFile().mkdirs();

        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(targetFile));

        Document document = new Document(pdfDoc);

        document.add(new Paragraph(new Text("The Revenant nominations list"))

                .setTextAlignment(TextAlignment.CENTER));

//        PdfDocument firstSourcePdf = new PdfDocument(new com.itextpdf.kernel.pdf.PdfReader(sourceFile));

        for (Map.Entry entry : catalogs.entrySet()) {

            Paragraph p = new Paragraph();

            p.addTabStops(new TabStop(540, TabAlignment.RIGHT, new DottedLine()));

            p.add(entry.getKey().toString());

            p.add(new Tab());

            p.add(String.valueOf(pdfDoc.getNumberOfPages() - 1));

            document.add(p);

        }

//        firstSourcePdf.close();

        int pages = pdfDoc.getNumberOfPages();

        document.close();

        return pages;

    }

    /***
     * PDF文件转PNG图片，全部页数
     *
     * @param pdfFilePath pdf完整路径
     * @param dpi dpi越大转换后越清晰，相对转换速度越慢(120/150/200 较清晰)
     */
    public static List<String> pdf2Image(String pdfFilePath, int dpi) {
        File file = new File(pdfFilePath);
        if (!file.exists()){
            return new ArrayList<>();
        }
        org.apache.pdfbox.pdmodel.PDDocument pdDocument = null;
        org.apache.pdfbox.rendering.PDFRenderer renderer = null;
        com.itextpdf.kernel.pdf.PdfReader reader = null;
        List<String> imgList = new ArrayList<>();
        try {
            String imgPdfPath = file.getParent();
            int dot = file.getName().lastIndexOf('.');
            // 获取图片文件名
            String imagePdfName = file.getName().substring(0, dot);

            pdDocument = org.apache.pdfbox.pdmodel.PDDocument.load(file);
            renderer = new org.apache.pdfbox.rendering.PDFRenderer(pdDocument);
            /* dpi越大转换后越清晰，相对转换速度越慢 */
            StringBuffer imgFilePath;
            reader = new com.itextpdf.kernel.pdf.PdfReader(pdfFilePath);
            int pages = pdDocument.getNumberOfPages();
            for (int i = 0; i < pages; i++) {
                String imgFilePathPrefix = imgPdfPath + File.separator + imagePdfName;
                imgFilePath = new StringBuffer();
                imgFilePath.append(imgFilePathPrefix);
                imgFilePath.append("_");
                imgFilePath.append((i + 1));
                imgFilePath.append(".png");
                File dstFile = new File(imgFilePath.toString());
                java.awt.image.BufferedImage image = renderer.renderImageWithDPI(i, dpi, ImageType.RGB);
                javax.imageio.ImageIO.write(image, "png", dstFile);
                imgList.add(imgFilePath.toString());
            }
//            pdDocument.close();

        } catch (IOException e) {
            log.error("pdf转换图片异常：{}", e.getMessage());
        }finally {
            try {
                reader.close();
                pdDocument.close();
            } catch (IOException e) {
                log.error("关闭文件失败：{}",e.getMessage());
            }
        }
        return imgList;
    }

    /***
     * 图片转pdf
     * @param source 源文件路径
     * @param target 输出文件路径
     */
    public static String img2Pdf(String source, String target) {
        File file = new File(source);
        if (!file.exists()) {
            log.error("文件不存在");
            return "";
        }
        Document document = null;
        PdfWriter writer = null;
        PdfDocument pdf = null;
        try {
            writer = new PdfWriter(target);
            pdf = new PdfDocument(writer);
            document = new Document(pdf);
            com.itextpdf.layout.element.Image image = new com.itextpdf.layout.element.Image(com.itextpdf.io.image.ImageDataFactory.create(source));
            image.setAutoScale(true);
            image.setAutoScaleHeight(true);
            image.setAutoScaleWidth(true);
            Paragraph p = new Paragraph().add(image);
            document.add(p);

        } catch (Exception e) {
            log.error("图片:{}，转pdf失败：{}", source, e.getMessage());
        } finally {
            //关闭文档
            document.close();
            pdf.close();
            try {
                writer.close();
            } catch (IOException e) {
                log.error("关闭流文件失败: {}",e.getMessage());
            }
        }
        return target;
    }

    /**
     * 下载文件，以压缩包形式下载
     * @param files 文件路径(new File（）后的路径)
     * @param fileNames 文件名（包含后缀）
     * @param response
     */
    public static void downZip(List<File> files,List<String> fileNames,HttpServletResponse response){
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=fileYsPackage.zip");
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(response.getOutputStream());
            byte[] data = new byte[1024];
//            List<File> files = new ArrayList<>();
//            files.add(new File("D:/upFiles/03f9ae4b-1be4-4dff-b0f5-ffefc4045715.pdf"));
//            files.add(new File("D:/upFiles/519a667d-e7de-423c-95ea-4007482fb9f2.pdf"));
//            files.add(new File("D:/upFiles/2aac27da-f0ce-49ef-a424-ea02fcdc41d2.pdf"));

            for (int i = 0; i < files.size(); i++) {
                if (!files.get(i).exists()){
                    continue;
                }
                int count;
                FileInputStream fis = new FileInputStream(files.get(i));
                BufferedInputStream bfs = new BufferedInputStream(fis);
                ZipEntry entry = new ZipEntry(fileNames.get(i).toString());
                zos.putNextEntry(entry);
                while ((count = bfs.read(data, 0, 1024)) != -1) {
                    zos.write(data, 0, count);
                }
                fis.close();
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            // 关闭流
            try {
                if (null != zos){
                    zos.flush();
                    zos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void deleteByCompleteUrl(String completeUrl){
        File file = new File(completeUrl);
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 下载文件，以压缩包形式下载
     * @param files inputStream文件流
     * @param fileNames 文件名
     * @param response
     */
    public static void downInputZip(List<InputStream> files,List<String> fileNames,HttpServletResponse response){
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=fileYsPackage.zip");
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(response.getOutputStream());
            byte[] data = new byte[1024];
            for (int i = 0; i < files.size(); i++) {
                int count;
                InputStream fis = files.get(i);
                if (fis == null){
                    return;
                }
                BufferedInputStream bfs = new BufferedInputStream(fis);
                ZipEntry entry = new ZipEntry(fileNames.get(i).toString());
                zos.putNextEntry(entry);
                while ((count = bfs.read(data, 0, 1024)) != -1) {
                    zos.write(data, 0, count);
                }
                fis.close();
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            // 关闭流
            try {
                if (null != zos){
                    zos.flush();
                    zos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /***
     * 设置文字水印
     *
     *@paramos 输出流
     *@paramsrcFile 源文件
     *@paramwaterMarkName 水印文字
     *@throwsDocumentException
     *@throwsIOException
     * */
    public static void setWordMark(OutputStream os, String srcFile, String waterMarkName, boolean isDefault) throws DocumentException , IOException {
        //如果你想直接输出到某个路径，将os参数改为descFile(具体输出路径)
        // BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(descFile)));
        PdfReader reader= new PdfReader(srcFile);

        PdfStamper stamper= new PdfStamper(reader, os);
        int total = reader.getNumberOfPages() + 1;

        PdfContentByte content;

        BaseFont base= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

        PdfGState gs= new PdfGState();

        for (int i = 1; i < total; i++) {
            content = stamper.getOverContent(i); //在内容上方加水印//content = stamper.getUnderContent(i);//在内容下方加水印

            if (isDefault){
                gs.setFillOpacity(0.05f); //透明度
                content.setTextMatrix(70, 200); // 水印文字位置
            }else {
                gs.setFillOpacity(0.05f); //透明度
                content.setTextMatrix(30, 160); // 水印文字位置
            }

            content.setGState(gs);
            content.beginText();
            content.setColorFill(BaseColor.BLACK);
            content.setFontAndSize(base, 15); // 水印文字大小

//            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 350, 55); // 水印文字位置-倾斜角度

            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 100, 100, 45);
            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 100, 300, 45);
            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 100, 500, 45);
            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 100, 700, 45);

            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 100, 45);
            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 300, 45);
            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 500, 45);
            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 700, 45);

            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 500, 100, 45);
            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 500, 300, 45);
            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 500, 500, 45);
            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 500, 700, 45);

            content.endText();
        }

        stamper.close();
    }

}
